<template>
  <el-dialog
    title="奖牌预估榜设置"
    class="gl_dialog_TitleLine gl_dl_footer"
    :visible.sync="dialogVisible"
    width="1100px"
    :close-on-click-modal="false"
    @close="closeDialog"
  >
    <div v-loading="loading" class="medal_estimate gl_px_20">
      <el-row>
        <el-col :span="16" :offset="4" class="gl_mb_20">
          <el-alert title="请填写每个大项最大拆分人数（组数），才可以生成奖牌预估榜，如填写数字为0则不分组" :closable="false" type="error" />
        </el-col>
      </el-row>
      <el-form v-if="tableData.length" ref="form" class="gl_form_mini estimate" size="medium" :model="vo" label-position="left" label-width="110px">
        <el-row :gutter="40">
          <el-col v-for="item in tableData" :key="item.id" :span="8">
            <el-form-item :label="item.name" :prop="item.id" :rules="rule">
              <el-input v-model="vo[item.id]" type="number" :min="0" :max="21474836" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-else-if="!loading" class="nodata">暂无项目数据</div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button type="primary" :disabled="!tableData.length" :loading="submitLoading" size="mini" @click="submitDialog">生成</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { Api_GET_EventsManagementCategoryQO } from '@/lib/form/game/swaggerForm';
import { api_GET_EventsManagementCategory } from '@/extend/api/gameswaggerApi/app';
import validator from '@/lib/validate/index.js';
import { errorText } from '@/lib';
export default {
  data() {
    return {
      gameId: '',
      parentId: '',
      tableData: [],
      listQO: new Api_GET_EventsManagementCategoryQO(),
      loading: false,
      submitLoading: false,
      dialogVisible: false,
      rule: [
        validator.required('最大拆分人数（组数）不能为空'),
        {
          validator(rule, value, callback) {
            // /^[1-9]\d*|0$/
            if (value && value !== '' && !/^([1-9]\d*|[0]{1,1})$/.test(value)) {
              callback(new Error('请输入正确的拆分人数（组数）值'));
            }
            callback();
          },
          trigger: 'blur'
        }],
      vo: {}
    };
  },
  methods: {
    getEventList() {
      const that = this;
      this.listQO.MaxResultCount = 1000;
      this.listQO.CompetitionId = this.gameId;
      this.listQO.Sorting = 'creationTime';
      this.loading = true;
      api_GET_EventsManagementCategory(this.listQO).then(res => {
        this.tableData = res.items || [];
        this.tableData.map(item => {
          that.vo[item.id] ? '' : that.$set(that.vo, item.id, 0);
        });
        this.loading = false;
      }, (error) => {
        this.loading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    open() {
      this.dialogVisible = true;
      this.gameId = this.$route.params.id;
      this.parentId = this.$route.params.parentId || '';
      this.getEventList();
    },
    closeDialog() {
      this.dialogVisible = false;
      this.vo = {};
      this.rules = {};
      this.tableData = [];
    },
    submitDialog() {
      const that = this;
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.exportMedalList();
        }
      });
    },
    handleMedalInput(obj) {
      const returnData = {
        CompetitionId: this.gameId,
        Settings: []
      };
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i];
        returnData.Settings.push({ CategoryId: item.id, Count: Number(obj[item.id]) });
      }
      return returnData;
    },
    exportMedalList() {
      const that = this;
      const tempUrl = `/api/excel`;
      const gameName = this.$route.query && this.$route.query.gameName || '';
      const fileName = (gameName ? gameName + ' ' : '') + '奖牌预估榜' + '.xlsx';
      const baseUrl = WEB_CONFIG.VUE_APP_SWAGGER_GAME_BASE;
      const MedalInput = this.handleMedalInput(this.vo);
      const GetMedalPredictionListInput = JSON.stringify(MedalInput);
      this.submitLoading = true;
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { reportName: 'MedalPredictionList', GetMedalPredictionListInput }, baseUrl).then(res => {
        this.submitLoading = false;
        that.$message({ type: 'success', message: '奖牌预估榜下载成功' });
        this.closeDialog();
      }).catch(error => {
        this.submitLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    }
  }
};
</script>

<style scoped>
.medal_estimate {
  min-height: 300px;
}
.nodata {
  text-align: center;
  height: 220px;
  line-height: 220px;
}
</style>
<style>
.estimate .el-form-item--medium .el-form-item__label {
  line-height: 20px;
}
</style>
